package com.wanli.agent.homepage;

import android.Manifest;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.text.InputFilter;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.material.bottomsheet.BottomSheetDialog;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.wanli.agent.R;
import com.wanli.agent.base.BaseActivity;
import com.wanli.agent.base.DataCallBack;
import com.wanli.agent.bean.BaseResponseBean;
import com.wanli.agent.bean.ImageBean;
import com.wanli.agent.bean.RateNewBean;
import com.wanli.agent.bean.StoreHuaBeiRateBean;
import com.wanli.agent.homepage.model.HomePageModelImpl;
import com.wanli.agent.homepage.model.IHomePageModel;
import com.wanli.agent.utils.Base64BitmapUtil;
import com.wanli.agent.utils.CashierInputFilterThree;
import com.wanli.agent.utils.GlideEngine;
import com.wanli.agent.utils.GlideUtils;
import com.wanli.agent.utils.PermissionsManager;
import com.wanli.agent.utils.ToastUtil;
import com.wanli.agent.widget.AppTitleBar;
import com.wanli.agent.widget.ViewLoading;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class StoreSpeedRateActivity extends BaseActivity {


    @BindView(R.id.title_bar)
    AppTitleBar titleBar;
    @BindView(R.id.tv_huabei_name)
    TextView tvHuabeiName;
    @BindView(R.id.edit_huabei_value)
    EditText editHuabeiValue;
    @BindView(R.id.tv_commit)
    TextView tvCommit;
    @BindView(R.id.ic_prcture_6)
    ImageView icPrcture6;
    @BindView(R.id.iv_11)
    ImageView iv_11;
    @BindView(R.id.tv_download_power_attorney_template)
    TextView tv_download_power_attorney_template;
    private IHomePageModel homePageModel;
    private String store_no;
    private BottomSheetDialog selectPicDialog;
    private String[] permissions;
    private PermissionsManager permissionsManager;
    private List<LocalMedia> mediaList = new ArrayList<>();
    private String yinsheng_change_pic;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_store_hua_bei_rate);
        ButterKnife.bind(this);
        initView();


    }

    public void initView() {
        store_no = getIntent().getStringExtra("store_no");
        int rate = getIntent().getIntExtra("rate", 0);
        homePageModel = new HomePageModelImpl();
        InputFilter[] filters = {new CashierInputFilterThree()};
        editHuabeiValue.setFilters(filters);
        requestShareMoneyRateNewMy();
//        requestGetStoreHuaBeiRate();
        permissionsManager = new PermissionsManager(StoreSpeedRateActivity.this);
        icPrcture6.setOnClickListener(v -> {
            showPictureSelectorDialog();
        });

        editHuabeiValue.setText(String.valueOf(rate));

        iv_11.setOnClickListener(view -> {
            Intent intent = new Intent(this, PreviewPicturesActivity.class);
            intent.putExtra("type","11");
            startActivity(intent);
        });

        tv_download_power_attorney_template.setOnClickListener(view -> {
            Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.iv_change_application_form_mb);
            saveScreenShot(bmp);
        });
    }


    public void requestShareMoneyRateNewMy() {
        homePageModel.requestShareMoneyRateNewMy(new DataCallBack<RateNewBean>() {
            @Override
            public void onSuccessful(RateNewBean bean) {
                setRateNewMy(bean);
            }

            @Override
            public void onFailed(String msg, String code) {

            }
        });
    }

    public void setRateNewMy(RateNewBean bean) {
        List<RateNewBean.DataBean> mList = bean.getData();
        for (RateNewBean.DataBean dataBean : mList) {
            switch (dataBean.getRule_type()) {
                case 13:
//                    tvHuabeiName.setText("微信/支付宝(参考" + dataBean.getRate() + ")");
                    break;
            }
        }
    }

//    public void requestGetStoreHuaBeiRate() {
//        homePageModel.requestGetStoreHuaBeiRate(store_no, new DataCallBack<StoreHuaBeiRateBean>() {
//            @Override
//            public void onSuccessful(StoreHuaBeiRateBean bean) {
//                editHuabeiValue.setText(bean.getData().getRate()*100);
//                if (!TextUtils.isEmpty(bean.getData().getRate())) {
//                    editHuabeiValue.setSelection(bean.getData().getRate().length());
//                }
//            }
//
//            @Override
//            public void onFailed(String msg, String code) {
//
//            }
//        });
//    }

    public void requestSetStoreHuaBeiRate(String dy_rate,String yinsheng_change_pic) {
        ViewLoading.showProgress(mActivity, "提交中......");
        homePageModel.requestSetStoreHuaBeiRate(store_no, dy_rate,yinsheng_change_pic, new DataCallBack<BaseResponseBean>() {
            @Override
            public void onSuccessful(BaseResponseBean bean) {
                ToastUtil.showShort(bean.getMsg());
                finish();
            }

            @Override
            public void onFailed(String msg, String code) {

            }
        });
    }

    @OnClick(R.id.tv_commit)
    public void onViewClicked() {
        String dy_rate = editHuabeiValue.getText().toString();

        if (TextUtils.isEmpty(dy_rate)) {
            ToastUtil.showShort("请输入费率");
            return;
        }
        if (TextUtils.isEmpty(yinsheng_change_pic)) {
            ToastUtil.showShort("请上传申请变更表图片");
            return;
        }

        requestSetStoreHuaBeiRate(dy_rate,yinsheng_change_pic);
    }
    private void showPictureSelectorDialog() {

        selectPicDialog = new BottomSheetDialog(mActivity, R.style.Dialog);
        selectPicDialog.getWindow().getAttributes().windowAnimations = R.style.commomDialog;
        View view = LayoutInflater.from(mActivity).inflate(R.layout.dialog_bottom_select_pictrue, null);
        // 相册
        TextView album = view.findViewById(R.id.tv_select_pictrue_album);
        // 相机
        TextView camera = view.findViewById(R.id.tv_select_pictrue_camera);
        // 取消
        TextView cancel = view.findViewById(R.id.tv_select_pictrue_cancel);

        album.setOnClickListener(v -> handlerPhotoAlbumClick());
        camera.setOnClickListener(v -> handlerCameraClick());
        cancel.setOnClickListener(v -> cancelPictureDialog());

        selectPicDialog.setContentView(view);
        selectPicDialog.show();
    }
    /**
     * 点击相册
     */
    private void handlerPhotoAlbumClick() {

        cancelPictureDialog();
        permissions = new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, //
                Manifest.permission.READ_EXTERNAL_STORAGE};

        if (PermissionsManager.checkPermissions(permissions)) {
            openPhotoAlbum();
            cancelPictureDialog();
            return;
        }
        permissionsManager.requestPermissionsEach(permissions);
        permissionsManager.setResultListener((allGranted, rejectPermissionList) -> {
            if (allGranted) {
                openPhotoAlbum();
                cancelPictureDialog();
            } else {
                permissionsManager.showDialog();
            }
        });
    }
    /**
     * 点击相机
     */
    private void handlerCameraClick() {

        permissions = new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, //
                Manifest.permission.CAMERA};

        if (PermissionsManager.checkPermissions(permissions)) {
            openCamera();
            cancelPictureDialog();
            return;
        }

        permissionsManager.requestPermissionsEach(permissions);
        permissionsManager.setResultListener((allGranted, rejectPermissionList) -> {
            if (allGranted) {
                openCamera();
                cancelPictureDialog();
            } else {
                permissionsManager.showDialog();
            }
        });
    }
    private void cancelPictureDialog() {
        if (selectPicDialog != null) {
            selectPicDialog.cancel();
        }
    }
    /**
     * 打开相册
     */
    private void openPhotoAlbum() {
        PictureSelector.create(StoreSpeedRateActivity.this)//
                .openGallery(PictureMimeType.ofImage())
                .loadImageEngine(GlideEngine.createGlideEngine())
                .theme(R.style.picture_default_style)//
                .maxSelectNum(1)//
                .minSelectNum(1)//
                .compress(true)//
                .selectionMedia(mediaList)//
                .cropCompressQuality(30)// 裁剪压缩质量 默认90 int
                .minimumCompressSize(100)// 小于20kb的图片不压缩
                .forResult(PictureConfig.CHOOSE_REQUEST);
    }
    /**
     * 打开相机
     */
    private void openCamera() {
        PictureSelector.create(StoreSpeedRateActivity.this)
                .openCamera(PictureMimeType.ofImage())
                .loadImageEngine(GlideEngine.createGlideEngine())
                .theme(R.style.picture_default_style)//
                .maxSelectNum(1)//
                .minSelectNum(1)//
                .compress(true)//
                .selectionMedia(mediaList)//
                .cropCompressQuality(30)// 裁剪压缩质量 默认90 int
                .minimumCompressSize(100)// 小于100kb的图片不压缩
                .forResult(PictureConfig.CHOOSE_REQUEST);
        cancelPictureDialog();

    }
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST:
                    // 图片、视频、音频选择结果回调
                    List<LocalMedia> mediaList = PictureSelector.obtainMultipleResult(data);
                    if (mediaList.size() > 0) {
                        String imgPath = mediaList.get(0).getCompressPath();
                        requestUploadFile(imgPath);
                    }
                    break;
            }
        }

    }
    /**
     * 上传图片
     */
    public void requestUploadFile(String imgPath) {
        ViewLoading.showProgress(mActivity, "上传中......");
        Bitmap bitmap = BitmapFactory.decodeFile(imgPath);
        String file = Base64BitmapUtil.bitmapToBase64(bitmap);
        homePageModel.requestUploadFile("store", file, new DataCallBack<ImageBean>() {
            @Override
            public void onSuccessful(ImageBean bean) {
                if (isDestroy()) {
                    return;
                }
                ToastUtil.showShort("上传成功");
                yinsheng_change_pic = bean.getData();
                GlideUtils.loadImage(mActivity, icPrcture6, imgPath);

            }

            @Override
            public void onFailed(String msg, String code) {

            }
        });
    }

    /**
     * 屏幕截图保存
     */
    private void saveScreenShot(Bitmap bitmap) {
        String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
        OutputStream outStream = null;
        String filename;//声明文件名
        //以保存时间为文件名
        Date date = new Date(System.currentTimeMillis());
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        filename = sdf.format(date);
        File file = new File(extStorageDirectory, filename + ".JPEG");//创建文件，第一个参数为路径，第二个参数为文件名
        try {
            outStream = new FileOutputStream(file);//创建输入流
            bitmap.compress(Bitmap.CompressFormat.JPEG, 90, outStream);
            outStream.close();

            Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
            Uri uri = Uri.fromFile(file);
            intent.setData(uri);
            mActivity.sendBroadcast(intent);

            Toast.makeText(mActivity, "保存成功 打开相册查看", Toast.LENGTH_SHORT).show();
        } catch (Exception e) {
            Toast.makeText(mActivity, "exception:" + e,
                    Toast.LENGTH_SHORT).show();

        }
    }

}
